<template>
  <div class="dialog">
    <el-dialog
      :title="equipmentName?equipmentName+'历史数据':'历史数据'"
      :visible.sync="showDialog"
      width="70%"
      top="0"
      :close-on-click-modal="false"
      @close="cancel"
    >
      <div class="mydialog">
        <div class="search-box">
          <div class="label-input mr-20 ml-20">
            <span class="label label-80">选择时间：</span>
            <div class="input">
              <el-date-picker
                v-model="date"
                type="daterange"
                :picker-options="pickerOptions"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                align="right"
                format="yyyy 年 MM 月 dd 日"
                value-format="yyyy/MM/dd"
              />
            </div>
          </div>
          <div class="search ml-20">
            <img
              src="~@/assets/action-bar-icon/search.png"
              @click="getforechartdata()"
            />
          </div>
        </div>
        <div class="con-main">
          <div class="con-side">
            <div
              v-for="(item,index) in echartSideList"
              :key="index"
              :class="item.ischecked?'con-side-item-select':'con-side-item'"
              @click="setitemchecked(index)"
            >{{ item.dataItemName }}</div>
          </div>
          <div class="con-echart">
            <Linechart
              :nowwidth="'100%'"
              :nowheight="'100%'"
              :cdata="lineObject"
              :y-axis="yaxiosdataList"
            />
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Linechart from "@/components/Echarts/components/linechart/chartYaxios.vue";
import physicalUnionDataApi from "@/api/physical-union-monitoring/physical-union-data/index";

export default {
  name: "",
  components: { Linechart },
  props: {
    show: {
      type: Boolean,
      default: false
    },
    equipmentName: {
      type: String,
      default: ""
    },
    dataItemId: {
      type: [String, Number],
      default: ""
    },
    equipmentCode: {
      type: [String, Number],
      default: ""
    }
  },
  data() {
    return {
      showDialog: this.show,
      date: [],
      // 查询设备所有关联数据项
      echartSideList: [],
      yaxiosdataList: [
        {
          type: "value",
          axisLabel: {
            fontSize: 10
          },
          min: 0
        }
      ],
      // echarts数据
      lineObject: {},
      paramsList: {},
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            }
          }
        ]
      }
    };
  },

  watch: {
    show(v) {
      this.showDialog = v;
      if (v) {
        this.getDataItemData();
      }
    }
  },
  created() {},
  mounted() {},
  methods: {
    // 获取当前设备下的dataitem,不带环境数据
    getDataItemData() {
      // let params = {
      //   ...this.paramsList,
      //   control: false
      // }
      // physicalUnionDataApi.getdataidechart(params).then(
      //   res => {
      //     if (res.data) {
      //       let listone = res.data
      //       listone.forEach(
      //         (selitem, selindex) => {
      //           if (selitem.dataItemId === Number(this.dataItemId)) {
      //             listone[selindex].ischecked = true
      //           } else {
      //             listone[selindex].ischecked = false
      //           }
      //         }
      //       )
      //       this.echartSideList = listone
      //       this.getforechartdata()
      //     }
      //   }
      // )
      physicalUnionDataApi.queryDataItem(this.equipmentCode).then(res => {
        if (res.data) {
          let listone = res.data;
          listone.forEach((selitem, selindex) => {
            if (selitem.dataItemId === Number(this.dataItemId)) {
              listone[selindex].ischecked = true;
            } else {
              listone[selindex].ischecked = false;
            }
          });
          this.echartSideList = listone;
          // this.echartSideList = [{
          //   category: "normal",
          //   control: false,
          //   dataItemId: 27407,
          //   dataItemName: "光照强度（智棚）",
          //   dataTypeId: 14,
          //   dataTypeName: "光照度",
          //   facilityId: 310,
          //   mainingControlType: "采集",
          //   organizationId: 54,
          //   sensorFacilityMapperId: 143,
          //   unitId: 1,
          //   visible: true
          // }]
          this.date = [
            this.$moment(new Date()).format("YYYY/MM/DD"),
            this.$moment(new Date()).format("YYYY/MM/DD")
          ];
          this.getforechartdata();
        }
      });
    },
    // 设置选中的至
    setitemchecked(i) {
      this.echartSideList[i].ischecked = !this.echartSideList[i].ischecked;
      this.getforechartdata();
    },
    // 从此开始循环获取折线图
    getforechartdata() {
      this.lineObject = {};
      this.yaxiosdataList = [
        {
          type: "value",
          offset: 0,
          axisLabel: {
            fontSize: 10
          },
          min: 0
        }
      ];
      this.echartSideList.forEach(item => {
        if (item.ischecked === true) {
          this.getDataLeft(item.dataItemId);
        }
      });
    },
    // 获取折线图
    getDataLeft(id) {
      let params = {
        dataItemId: id
      };
      if (this.date[0]) {
        // params.startTime = this.dateToFormat(this.searchList.date[0])
        // params.endTime = this.dateToFormat(this.searchList.date[1])
        params.startTime = this.date[0];
        params.endTime = this.date[1];
      } else {
        var time = new Date();
        let date = this.$moment(time).format("YYYY/MM/DD");
        params.startTime = date;
        params.endTime = date;
      }
      physicalUnionDataApi.queryHistory(params).then(res => {
        this.handleLine(res.data);
      });
    },
    getDataItemName(data) {
      var index = this.echartSideList.findIndex(a => a.dataItemId === data);
      var name = "";
      if (index !== -1) {
        name = this.echartSideList[index]["dataItemName"];
      }
      return name;
    },
    // 折线图数据处理
    handleLine(list) {
      let xAxisdata = [];
      let xData = [""];
      let nowindex = 0;
      if (this.lineObject.seriesData) {
        nowindex = this.lineObject.seriesData.length;
      }
      let seriesData = [
        {
          name:
            list && list.length > 0
              ? this.getDataItemName(list[0].dataItemId)
              : "",
          type: "line",
          data: [],
          yAxisIndex: nowindex,
          barWidth: 10
        }
      ];
      list.forEach(item => {
        seriesData[0]["data"].push(item.value);
        let ggdate = this.$moment(item.collectDatetime).format(
          "YYYY-MM-DD HH:ss:mm"
        );
        xAxisdata.push(ggdate);
      });
      let oldserData = [];
      if (this.lineObject.seriesData) {
        oldserData = JSON.parse(JSON.stringify(this.lineObject.seriesData));
      }
      // 新增一条y轴
      let oldyaxioslist = JSON.parse(JSON.stringify(this.yaxiosdataList));
      let offset = 0;
      // if(oldserData.length === )
      if (oldserData.length >= 2) {
        offset = (oldserData.length - 1) * 26;
      }
      // let offset = oldserData.length * 20
      if (oldserData.length > 0) {
        this.yaxiosdataList = [
          ...oldyaxioslist,
          {
            type: "value",
            offset: offset,
            axisLabel: {
              fontSize: 10
            },
            min: 0
          }
        ];
      }
      // 新增一条数据
      this.lineObject = {
        xAxisdata: xAxisdata,
        xData: xData,
        seriesData: [...seriesData, ...oldserData]
      };
      // this.yaxiosdataList.push(yaxiosdata)
    },
    close() {
      this.$emit("closeDialog");
    },
    cancel() {
      this.$emit("closeDialog");
    }
  }
};
</script>

<style lang="scss" scoped>
@import "~@/styles/variables.scss";
// .#005d7b
::v-deep .el-dialog {
  background-color: #005d7b;
  .el-dialog__title {
    color: #fff;
  }
}
.search-box {
  display: flex;
  align-items: center;
  // margin-left: 20px;
  flex-wrap: wrap;
  position: relative;
  color: #fff;
  .label-input {
    display: flex;
    align-items: center;
    margin: 10px 10px;
    .label {
      min-width: 100px;
      white-space: nowrap;
      text-align: end;
      padding: 0 10px;
    }
  }
  .search {
    display: flex;
    align-items: center;
    cursor: pointer;
    img {
      height: 30px;
    }
  }
}
.mydialog {
  width: 100%;
  height: 500px;
  .con-main {
    height: calc(100% - 60px);
    width: 100%;
    display: flex;
    justify-content: space-between;
    .con-side {
      width: 40px;
      height: 100%;
      overflow-y: auto;
      overflow-x: hidden;
      font-size: 16px;
      .con-side-item {
        width: 40px;
        // height: 100px;
        color: aliceblue;
        font-weight: 500;
        display: flex;
        flex-direction: column;
        background-color: #004860;
        border: aliceblue 1px solid;
        padding-right: 5px;
        padding-left: 5px;
        padding-top: 10px;
        padding-bottom: 10px;
        text-align: center;
        cursor: pointer;
      }
      .con-side-item-select {
        width: 40px;
        // height: 100px;
        color: aliceblue;
        font-weight: 500;
        display: flex;
        flex-direction: column;
        background-image: linear-gradient(#0cbac7, #4ceffe, #0bb9c6);
        border: aliceblue 1px solid;
        padding-right: 5px;
        padding-left: 5px;
        padding-top: 10px;
        padding-bottom: 10px;
        text-align: center;
        cursor: pointer;
      }
    }
    .con-side::-webkit-scrollbar {
      display: none;
    }
    .con-echart {
      width: calc(100% - 80px);
      height: 100%;
    }
  }
}
::v-deep .el-dialog__close {
  font-size: 20px !important;
}
</style>
